import { ref, computed } from 'vue'

// 用户信息状态
const user = ref(null)
const token = ref(null)

// 从 sessionStorage 初始化用户信息
const initAuth = () => {
  const storedUser = sessionStorage.getItem('pmp-user')
  const storedToken = sessionStorage.getItem('pmp-token')
  
  if (storedUser) {
    try {
      user.value = JSON.parse(storedUser)
    } catch (error) {
      console.error('解析用户信息失败:', error)
      user.value = null
    }
  }
  
  if (storedToken) {
    token.value = storedToken
  }
}

// 设置用户信息
const setUser = (userData) => {
  user.value = userData
  sessionStorage.setItem('pmp-user', JSON.stringify(userData))
}

// 设置 token
const setToken = (tokenValue) => {
  token.value = tokenValue
  sessionStorage.setItem('pmp-token', tokenValue)
}

// 清除用户信息
const clearAuth = () => {
  user.value = null
  token.value = null
  sessionStorage.removeItem('pmp-user')
  sessionStorage.removeItem('pmp-token')
}

// 检查是否为管理员
const isAdmin = computed(() => {
  return user.value && user.value.username === 'admin'
})

// 检查是否已登录
const isLoggedIn = computed(() => {
  return user.value && token.value
})

// 获取当前用户
const getCurrentUser = computed(() => {
  return user.value
})

// 初始化认证状态
initAuth()

export function useAuth() {
  return {
    user: computed(() => user.value),
    token: computed(() => token.value),
    isAdmin,
    isLoggedIn,
    getCurrentUser,
    setUser,
    setToken,
    clearAuth
  }
}
